<?php
class Libs_Land
{
    /**
     *  Land status for active
     */
    const STATUS_APPROVAL = 1;
    
    /**
     *  Land status for pending
     */
    const STATUS_PENDING = 2;
    
	private static $instance;
	
	private function __construct(){
		
	}
	
    /**
     *
     * @return Libs_Land 
     */
	public static function getInstance(){
		if(!isset(self::$instance)){
			self::$instance = new Libs_Land();
		}
		return self::$instance;
	}
	
	public function getLandById($id)
	{
		return LandTable::getInstance()->findOneById($id);
	}
	
	/**
	 * get current page from request url
	 */
	public function get_page()
	{
		return Request::current()->param('page',1);
	}
	
	/**
	 * return current list location
	 */
	public function get_location()
	{
		return Doctrine_Query::create()
						->from('Location l')
						->where('l.parent_id = ?',0)
						->orderBy('l.name ASC')->execute();
	}
	
	public function get_list($view,$params = null)
	{
		$query = Doctrine_Query::create()
								->from('Land l');
								
		if(!is_null($params)){
			if(isset($params['location']) && is_numeric($params['location'])){
				$query->addWhere('l.location_id = ?',$params['location']);
			}
			
			if(isset($params['transaction_type']) && !empty($params['transaction_type'])){
				$query->addWhere('l.transaction_type = ?',$params['transaction_type']);
			}
			
			if(isset($params['q']) && strlen(trim($params['q'])) > 0){
				$query->addWhere('l.title LIKE ?',"%{$params['q']}%");
			}
            
            if(isset($params['direction']) && strlen(trim($params['direction'])) > 0){
                $query->addWhere('l.direction = ?',$params['direction']);
            }
            
            if(isset($params['from_price']) &&is_numeric($params['from_price'])){
                $query->addWhere('l.price >= ?',$params['from_price']);
            }
            
            if(isset($params['to_price']) && is_numeric($params['to_price'])){
                $query->addWhere('l.price <= ?',$params['to_price']);
            }
            
            if(!isset($params['status'])){
                $params['status'] = Libs_Land::STATUS_APPROVAL;
            }
            
            $query->addWhere('l.status = ?', $params['status']);
            
            if(isset($params['area']) && is_numeric($params['area'])){
                $operators = array('>=','<=','=');
                $operator = in_array($params['operator'],$operators) ? $params['operator'] : '>=';
                
                $query->addWhere('l.area '.$operator.' ?',$params['area']);
            }
		}
		
		$query->orderBy('l.created DESC');
		
		$pager = new Doctrine_Pager($query, $this->get_page(),Tools::get_admin_item_page());

		$pagerRange = new Doctrine_Pager_Range_Sliding(array('chunk' => 5),$pager);
        
        if(Request::current()->directory() == 'admin'){
            $urlMask = Route::url('admin-land-list',array('action' => Request::current()->action(),'page' => '{%page_number}','query' => '{%query}'));
        }else{
            $action = (Request::current()->action() == 'search') ? 'search': 'page';
            $urlMask = Route::url('client-land-list',array('action' => $action,'page' => '{%page_number}','query' => '{%query}'));
        }
		
		$pagination = new CustomPagerLayout($pager, $pagerRange,$urlMask);
		$pagination->setTemplate('<a href="{%url}" class="number" title="Trang {%page}">{%page}</a>');
        $pagination->setSelectedTemplate('<a href="{%url}" class="number current" title="Trang {%page}">{%page}</a>');
        
        return View::factory($view)->set(array(
        	'lands' => $pager->execute(),
        	'pagination' => $pagination->display(array(
        			'query' => http_build_query(Request::current()->query())
        		),true)
        ));
	}
    

    public function saveLand(array $post,$isNew = true)
    {
        if(!Api::load('user')->is_logged())
        {
            FlashMessage::getInstance()->add('Bạn cần đăng nhập để đăng tin trên Wharfland.');
            return false;
        }
        
        if($isNew){
            return $this->addNewLand($post);
        }else{
            return $this->updateLand($post);
        }
    }
    
    public function addNewLand(array $formData)
    {
        try{
			$land = new Land();
            
            if(isset($formData['price'])){
                //format my price
                $formData['price'] = str_replace('.','', $formData['price']);
            }
            
			$land->fromArray(Arr::extract($formData, array('title','direction','short_description','transaction_type',
														  'contact_name','contact_phone','location_id',
														  'price','area','description','status')));
			
            $user_info = Api::load('user')->get_user_info();
            
            /**
             * if user not login with admin role, and then set land status to pending
             */
            if(!Api::load('user')->has_role($user_info['id'],'admin'))
            {
                $land->status = Libs_Land::STATUS_PENDING;
            }
            
			//get first image from description content
			preg_match('/<\s*img [^\>]*src\s*=\s*(["\'])(.*?)\1/',Arr::get($formData,'description'),$matches);
			if(is_array($matches) && !empty($matches)){
				$land->image = $matches[2];
			}else{
				$land->image = null;	
			}
			
			//remove invalid html tag in your description
			$land->description = Security::xss_clean(Arr::get($formData,'description'));
            
            $land->created_by = $user_info['id'];
            
            $land->land_type_id = Arr::get($formData, 'land_type');
            
			$land->save();
			return true;
		}catch (Doctrine_Validator_Exception $ex){
			FlashMessage::getInstance()->add($ex->getMessage());
		}
		return false;
    }
    
    public function updateLand(array $formData)
    {
        $land_id = Arr::get($formData,'id');
		if(!is_numeric($land_id)){
			FlashMessage::getInstance()->add("Land not found",FlashMessage::WARNING);
		}else{
			$land = LandTable::getInstance()->findOneById($land_id);
			if(!$land){
				FlashMessage::getInstance()->add("Land not found",FlashMessage::WARNING);	
			}else{
				try{
                    
                    if(isset($formData['price'])){
                        //format my price
                        $formData['price'] = str_replace('.','', $formData['price']);
                    }
                    
					$land->setArray(Arr::extract($formData,array(
						  'title','direction','short_description','transaction_type',
						  'contact_name','contact_phone','location_id',
						  'price','area','description','status'
					)));
                    
                    $user_info = Api::load('user')->get_user_info();
            
                    /**
                     * if user not login with admin role, and then set land status to pending
                     */
                    if(!Api::load('user')->has_role($user_info['id'],'admin'))
                    {
                        $land->status = Libs_Land::STATUS_PENDING;
                    }
					
					//get first image from description content
					preg_match('/<\s*img [^\>]*src\s*=\s*(["\'])(.*?)\1/',Arr::get($formData,'description'),$matches);
					if(is_array($matches) && !empty($matches)){
						$land->image = $matches[2];
					}else{
						$land->image = null;
					}	
					
					//remove invalid html tag in your description
                    $land->description = Security::xss_clean(Arr::get($formData,'description'));
					
                    $land->land_type_id = Arr::get($formData, 'land_type');
                    
					$land->save();
					return true;
				}catch (Doctrine_Validator_Exception $ex){
					//only for debug	
                    die($ex->getMessage());
					FlashMessage::getInstance()->add($ex->getMessage());				
				}
			}
		}
		
		return false;
    }
    
    public function get_land_type(){
        if ($landType = LandTypeTable::getInstance()->findAll()) {
            return $landType->toArray();
        }

        return array();
    }
    
    /**
     * Get Five Land by User id
     * @param type $id
     * @return type 
     */
    public function get_land_by_user($id)
    {
        if(!is_numeric($id)){
            return false;
        }
        return Doctrine_Query::create()
                ->from('Land l')
                ->where('l.created_by = ?',$id)
                ->limit(5)->execute();
    }
    
    public function get_land_status_as_array()
    {
        return array(
            self::STATUS_APPROVAL => 'Đã duyệt',
            self::STATUS_PENDING  => 'Chờ duyệt'
        );
    }
}